<template>
  <div>
    <div class="auth-page">
      <div class="container page">
        <div class="row">
          <div class="col-md-6 offset-md-3 col-xs-12">
            <h1 class="text-xs-center">
              {{ isLogin ? "Sign in" : "Sign up" }}
            </h1>
            <p class="text-xs-center">
              <!-- <a href="">Have an account?</a> -->
              <nuxt-link v-if="isLogin" to="/register"
                >Need a account?</nuxt-link
              >
              <nuxt-link v-else to="/login">Have a account?</nuxt-link>
            </p>

            <ul class="error-messages">
              <!-- 此处的messages是错误字段数组，field是发生错误的地方 -->
              <template v-for="(messages, field) in errors">
                <li v-for="(message, index) in messages" :key="index">
                  {{ field }} {{ message }}
                </li>
              </template>
            </ul>

            <form @submit.prevent="onSubmit">
              <!-- 阻止默认的同步提交行为，而是我们自己去发起异步请求来提交表单 -->
              <fieldset class="form-group" v-if="!isLogin">
                <input
                  class="form-control form-control-lg"
                  type="text"
                  placeholder="Your Name"
                  v-model="user.username"
                />
              </fieldset>
              <fieldset class="form-group">
                <input
                  class="form-control form-control-lg"
                  type="email"
                  placeholder="Email"
                  v-model="user.email"
                  required
                />
              </fieldset>
              <fieldset class="form-group">
                <input
                  class="form-control form-control-lg"
                  type="password"
                  placeholder="Password"
                  v-model="user.password"
                  required
                  minlength="8"
                />
              </fieldset>
              <button class="btn btn-lg btn-primary pull-xs-right">
                {{ isLogin ? "Sign in" : "Sign up" }}
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { login,register } from "@/api/user";
const Cookie = process.client ? require('js-cookie') : undefined
export default {
  middleware:'notAuthenticated',
  name: "LoginIndex",
  computed: {
    isLogin() {
      return this.$route.name === "login";
    }
  },
  data() {
    return {
      user: {
        email: "",
        password: "",
        username:''
      },
      errors: {},
    };
  },
  methods: {
    // 提交表单，请求登录
    async onSubmit() {
      try {
        const { data } = this.isLogin === true?
        await login({
          user: this.user
        }) : 
        await register({
          user: this.user
        })
        // console.log(data); //拿到登录成功后返回的用户数据,数据格式为：data:{user:{...}}
        // 将拿到的用户信息存入到vuex中
        this.$store.commit('setUser', data.user)

        // 为了防止刷新页面数据丢失，我们需要把数据持久化
        // 这样一来，页面刷新时我们就可以再去cookie拿数据实现持久化
        Cookie.set('user',data.user)

        // 跳转到首页
        this.$router.push("/");
      } catch (err) {
        // console.log(err);
        this.errors = err.response.data.errors
        // 错误信息格式：
        // err{
        //   ...
        //   response:{
        //     ...
        //     data:{
        //       errors:{
        //         xxxx(错误的名称):['错误的内容1','错误的内容2'....]
        //       }
        //     }
        //   }
        // }
      }
    },
  },
};
</script>

<style scoped></style>
